import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:talk/routers/routers2.dart';

/// fluro的路由跳转工具类
class NavigatorUtils {
  static final FluroRouter router = FluroRouter();

  // 已有的push方法（保持不变）
  static void push(BuildContext context, String path,
      {bool replace = false, bool clearStack = false, Object? arguments}) {
    unfocus();
    Routes.router.navigateTo(context, path,
      replace: replace,
      clearStack: clearStack,
      transition: TransitionType.native,
      routeSettings: RouteSettings(
        arguments: arguments,
      ),
    );
  }

  /// 新增：带返回值的页面跳转方法
  /// [context]：上下文
  /// [path]：路由路径
  /// [onResult]：返回值回调（页面关闭时触发）
  /// [replace]：是否替换当前路由
  /// [clearStack]：是否清除路由栈
  /// [arguments]：传递的参数
  static void pushResult(
      BuildContext context,
      String path,
      void Function(Object?) onResult, {  // 回调接收返回值（可能为null）
        bool replace = false,
        bool clearStack = false,
        Object? arguments,
      }) {
    unfocus();
    // 调用Fluro的navigateTo并监听返回值
    Routes.router.navigateTo(
      context,
      path,
      replace: replace,
      clearStack: clearStack,
      transition: TransitionType.native,
      routeSettings: RouteSettings(
        arguments: arguments,
      ),
    ).then((result) {  // 页面关闭后触发
      onResult(result);  // 将返回值传递给回调
    }).catchError((error) {
      debugPrint('路由跳转错误: $error');
      onResult(null);  // 错误时返回null
    });
  }

  // 已有的其他方法（保持不变）
  static void unfocus() {
    FocusManager.instance.primaryFocus?.unfocus();
  }

  static void goBack(BuildContext context) {
    unfocus();
    Navigator.pop(context);
  }

  static void pushResult1(BuildContext context, String path, void Function(Object) function,
      {bool replace = false, bool clearStack = false, Object? arguments}) {
    unfocus1();
    FluroRouter().navigateTo(context, path,
      replace: replace,
      clearStack: clearStack,
      transition: TransitionType.native,
      routeSettings: RouteSettings(
        arguments: arguments,
      ),
    ).then((Object? result) {
      if (result == null) {
        return;
      }
      function(result);
    }).catchError((dynamic error) {
      debugPrint('$error');
    });
  }

  static void goBackWithParams(BuildContext context, Object result) {
    print("返回。。。。");
    unfocus();
    Navigator.pop<Object>(context, result);
  }

  static void unfocus1() {
    FocusManager.instance.primaryFocus?.unfocus();
  }
}